<template>
    <div class="slider">
      <div 
        class="item" 
        :style="carouselStyle"
        @mouseenter="handleMouseEnter"
        @mouseleave="handleMouseLeave">
        <div 
          v-for="(item, index) in img" 
          :key="index" 
          :class="index === current ? 'active' : 'normal'"
        >
          <img :src="item.src" :alt="item.alt" />
        </div>
      </div>
      
      <el-button class="prev" type="primary" :icon="ArrowLeft" circle @click="lastItem"></el-button>
      <el-button class="next" type="primary" :icon="ArrowRight" circle @click="nextItem"></el-button>
    </div>
  </template>
  
  <script setup>
  import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
  import { computed, onMounted, reactive, ref } from 'vue';
  
  defineOptions({
    name: 'Slider'
  });
  
  const img = reactive([
    { src: require('@/assets/image/slide-img/01.jpg'), alt: '' },
    { src: require('@/assets/image/slide-img/02.jpg'), alt: '' },
    { src: require('@/assets/image/slide-img/03.jpg'), alt: '' },
    { src: require('@/assets/image/slide-img/04.jpg'), alt: '' },
  ]);
  
  const length = img.length || null;
  let timer;
  const current = ref(0);
  
  const carouselStyle = computed(() => {
    return {
      transition: 'transform 0.5s ease-in-out',
    };
  });
  
  function nextItem() {
    current.value = (current.value + 1) % length;
    clearInterval(timer);
    autoSlide();
  }
  
  function lastItem() {
    current.value = (current.value - 1 + length) % length;
    clearInterval(timer);
    autoSlide();
  }
  
  function autoSlide() {
    timer = setInterval(() => {
      nextItem();
    }, 2000);
  }
  
  function handleMouseEnter() {
    clearInterval(timer);
  }
  
  function handleMouseLeave() {
    autoSlide();
  }
  
  onMounted(() => {
    autoSlide();
  });
  </script>
  
  <style lang="scss" scoped>
  .slider {
    width: 100%;
    height: 500px;
    position: relative;
    overflow: hidden; /* 防止内容溢出 */
  
    .item {
      width: 100%;
      height: 100%;
      display: flex;
      position: relative;
  
      div {
        position: absolute; /* 绝对定位，以覆盖其他项 */
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0; /* 默认不透明 */
        transition: opacity 0.5s ease-in-out; /* 过渡效果 */
  
        &.active {
          opacity: 1; /* 当前项完全可见 */
        }
      }
  
      img {
        width: 100%;
        height: 100%;
        object-fit: cover; /* 保持图片比例并覆盖整个区域 */
      }
    }
  
    .prev {
      left: 10px;
    }
  
    .next {
      right: 10px;
    }
  
    button {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      background-color: rgba(0, 0, 0, 0.2);
      color: white;
      border: none;
      padding: 10px;
      cursor: pointer;
      border-radius: 50%;
      z-index: 100;
  
      &:hover {
        background-color: rgba(0, 0, 0, 0.5);
      }
    }
  }
  </style>
  